package com.grayscale.core.rule;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.grayscale.core.adapt.GrayScaleRuleAdapt;
import com.grayscale.core.enums.GrayScaleTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liuli
 * @date 2022/2/11
 * 参数格式  HH:mm:ss (24小时制)
 */
public class GrayScaleTimeRule implements GrayScaleRuleAdapt {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private int sTime = 0;
    private int pTime = 0;

    @Override
    public boolean process(String... parameter) {
        if (!check(parameter[0])){
            return false;
        }
        GrayScaleTypeEnum grayScaleTypeEnum = GrayScaleTypeEnum.getByType(parameter[1]);
        switch (grayScaleTypeEnum) {
            case BEFORE_TIME:
                if (sTime > pTime){
                    return false;
                }
                break;
            case AFTER_TIME:
                if (sTime < pTime){
                    return false;
                }
                break;
        }
        return true;
    }

    @Override
    public boolean check(String parameter) {
        try {
             String dateStr = DateUtil.format(new DateTime() , DatePattern.NORM_DATETIME_PATTERN);
             sTime = Integer.parseInt(dateStr.split("\\s")[1].replaceAll(":",""));
             pTime = Integer.parseInt(parameter.replaceAll(":",""));
        } catch (Exception e) {
            log.error("parameter format error:{} {}",parameter,e);
            return false;
        }
        return true;
    }
}
